package com.seh.usercenter.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.seh.usercenter.domain.JsonResult;
import com.seh.usercenter.domain.Result;
import com.seh.usercenter.dto.UserDTO;
import com.seh.usercenter.entity.User;
import com.seh.usercenter.service.UserServiceImpl;
import com.seh.usercenter.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Value("${file-save-path}")
    private String fileSavePath;

    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 用户注册
     *
     * @param
     * @return
     */
    @PostMapping("/register")
    public String register(@RequestParam String password, @RequestParam String username,
                           @RequestParam String phone, @RequestParam String code) {
        boolean verifyCode = userService.verifyCode(phone, code);
        if (verifyCode) {
            if (userService.judgePhoneIsPresent(phone)) {
                User user = new User();
                user.setPhone(phone);
                user.setUsername(username);
                user.setPassword(password);
                userService.register(user);
                return "注册成功";
            } else {
                return "手机号已经注册";
            }
        } else {
            return "注册失败，验证码错误或已经过期";
        }

    }

    /**
     * 通过用户id查询用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/findUserInfoById/{userId}")
    public UserDTO findUserInfoById(@PathVariable Integer userId) {
        UserDTO userInfo = userService.findUserInfoById(userId);
        return userInfo;
    }

    /**
     * 通过用户id查询用户信息
     *
     * @param userId
     * @return
     */

    @GetMapping("/findUserInfoByIdByMyBatis/{userId}")
    public Result<UserDTO> findUserInfoByIdByMyBatis(@PathVariable Integer userId) {
        UserDTO userDTO = userService.findUserInfoByIdByMyBatis(userId);
        return ResultUtil.userInfo(userDTO);
    }

    /**
     * 用来判断用户输入的手机号是否为‘合法的手机号’
     *
     * @param phone
     * @return
     */
    @GetMapping("/judgePhone/{phone}")
    public boolean judgePhone(@PathVariable String phone) {
        boolean judgePhoneNum = userService.judgePhoneNum(phone);
        return judgePhoneNum;
    }

    /**
     * 判断手机号是否已经注册过
     *
     * @param phone
     * @return
     */
    @GetMapping("/judgePhoneIsPresent/{phone}")
    public boolean judgePhoneIsPresent(@PathVariable String phone) {
        Boolean isPresent = userService.judgePhoneIsPresent(phone);
        return isPresent;
    }

    /**
     * 通过用户主键id修改用户信息
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody UserDTO userDTO) {
        String result = userService.updateUserInfo(userDTO);
        return result;
    }

    /**
     * 通过用户id
     * 删除用户信息
     * 此删除方法为逻辑删除
     *
     * @param userId
     * @return
     */
    @GetMapping("/deleteUser/{userId}")
    public String deleteUser(@PathVariable Integer userId) {
        String s = userService.deleteUserInfo(userId);
        return s;
    }

    /**
     * 通过密码登录
     *
     * @param phone
     * @param password
     * @return
     */
    @GetMapping("/loginByPassword")
    public UserDTO loginByPassword(@RequestParam("phone") String phone,
                                   @RequestParam("password") String password) {
        Boolean aBoolean = userService.judgePhoneIsPresent(phone);
        if (!aBoolean) {
            UserDTO userDTO = userService.loginByPassword(phone, password);
            if (userDTO != null) {
                return userDTO;//登录成功，返回给前端用户数据
            }
        }
        return null;//登录失败，返回空值
    }

    /**
     * 通过验证码登录
     *
     * @param phone
     * @param code
     * @return
     */
    @GetMapping("/loginByCode")
    public UserDTO loginByCode(@RequestParam("phone") String phone,
                               @RequestParam("code") String code) {
        Boolean aBoolean = userService.judgePhoneIsPresent(phone);
        if (!aBoolean) {
            UserDTO userDTO = userService.loginByCode(phone, code);
            if (userDTO != null) {
                return userDTO;//登录成功，返回给前端用户数据
            }
        }
        return null;//登录失败，返回空值
    }

    /**
     * 用户输入手机号
     * 发送四位数验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/sendSms")
    public String sendSms(@RequestParam String phone) {
        boolean result = userService.sendSms(phone);
        if (result) {
            return "验证码发送成功";
        } else {
            return "验证码发送失败";
        }
    }

    /**
     * 检验用户输入的验证码与第三方平台发送的验证码是否相同
     *
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/loginBySms")
    public String loginBySms(@RequestParam String phone,
                             @RequestParam String code) {
        boolean verifyCode = userService.verifyCode(phone, code);
        if (verifyCode) {
            return "登录成功";
        } else {
            return "验证码错误或已失效";
        }
    }

    /**
     * 用户上传头像
     *
     * @param file
     * @param userId
     * @param request
     * @return
     */
    @PostMapping("/uploadPic")
    public JsonResult uploadPic(@RequestParam("file") MultipartFile file,
                                @RequestParam("userId") Integer userId, HttpServletRequest request) {
//        UserDTO userDTO = userService.findUserInfoByIdByMyBatis(userId);
        UserDTO userDTO = userService.findUserInfoById(userId);

        //1.后半段目录：  2020/03/15
        String directory = simpleDateFormat.format(new Date());
        /**
         *  2.文件保存目录  E:/images/2020/03/15/
         *  如果目录不存在，则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        log.info("图片上传，保存位置：" + fileSavePath + directory);
        //3.给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        //4.创建这个新文件
        File newFile = new File(fileSavePath + directory + "/" + newFileName);
        //5.复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picture_test/" + directory + "/" + newFileName;

            userDTO.setPic(url);
            userDTO.setPassword(null);
            userDTO.setPayPassword(null);
            userService.updateUserInfo(userDTO);

            log.info("图片上传，访问URL：" + url);
            return JsonResult.builder().data(url).message("上传成功！").code("1").build();
        } catch (IOException e) {
            return JsonResult.builder().data(null).message("IO异常！").code("-1").build();
        }
    }

    /**
     * 忘记密码，修改密码
     *
     * @param phone
     * @param password
     * @param code
     * @return
     */
    @PostMapping("/forgetSoChangePassword")
    public String forgetSoChangePassword(@RequestParam String phone,
                                         @RequestParam String password,
                                         @RequestParam String code) {
        String s = userService.forgetSoChangePassword(phone, password, code);
        return s;
    }

    /**
     * 修改ip地址
     * @param ipAddress
     * @return
     */
    @PostMapping("/updateIpAddressByUserId")
    public String updateIpAddressByUserId(@RequestParam Integer userId, @RequestParam String ipAddress) {
        return userService.updateIpAddressByUserId(userId, ipAddress);
    }
}
